package eproject.mm.com.projectsupervision.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.header.StoreHouseHeader;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.google.gson.Gson;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.activity.MessageContentActivity;
import eproject.mm.com.projectsupervision.activity.ProblemInfoActivity;
import eproject.mm.com.projectsupervision.activity.ProjectActivity;
import eproject.mm.com.projectsupervision.activity.ProjectSelectActivity;
import eproject.mm.com.projectsupervision.adapter.BaseRecyclerViewAdapter;
import eproject.mm.com.projectsupervision.adapter.ProjectSelectAdapter;
import eproject.mm.com.projectsupervision.adapter.RecyclerViewAdapter;
import eproject.mm.com.projectsupervision.util.HttpUtil;



/**
 * Created by momotea on 2018/3/19.
 */

public class BaseFragment extends LazyFragment implements BaseRecyclerViewAdapter.onItemClickListener{

    RecyclerView rv_list;
    BaseRecyclerViewAdapter adapter;

    int page = 1;
    String type;
    String projectId,notclick = "0";

    LoadingDialog loadingDialog = null;
    private PtrClassicFrameLayout ptrFrameLayout;

    List listData = new ArrayList();
    //添加Header和Footer的封装类
    private RecyclerAdapterWithHF mAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        if(getArguments() != null){
            type = getArguments().getString("type","");
            projectId = getArguments().getString("projectId","");
            notclick = getArguments().getString("notclick","0");
        }
        return inflater.inflate(R.layout.fragment_base, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        rv_list = (RecyclerView)getView().findViewById(R.id.rv_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_list.setLayoutManager(layoutManager);

        adapter = new BaseRecyclerViewAdapter(getContext(), listData);
        mAdapter = new RecyclerAdapterWithHF(adapter);

        adapter.setOnItemClickLitsener(this);

        rv_list.setAdapter(mAdapter);

        ptrFrameLayout = (PtrClassicFrameLayout)getView().findViewById(R.id.ptrFL_list);

//        final StoreHouseHeader header = new StoreHouseHeader(getContext());
//        header.setPadding(0, 15, 0, 0);
//        header.initWithString("loading...");
//        header.setTextColor(Color.GRAY);
//        ptrFrameLayout.setHeaderView(header);
//        ptrFrameLayout.addPtrUIHandler(header);
//        ptrFrameLayout.setLoadMoreEnable(false);

        //下拉刷新支持时间
        ptrFrameLayout.setLastUpdateTimeRelateObject(this);
        //下拉刷新一些设置 详情参考文档
        ptrFrameLayout.setResistance(1.7f);
        ptrFrameLayout.setRatioOfHeaderHeightToRefresh(1.2f);
        ptrFrameLayout.setDurationToClose(200);
        ptrFrameLayout.setDurationToCloseHeader(1000);
        // default is false
        ptrFrameLayout.setPullToRefresh(false);
        // default is true
        ptrFrameLayout.setKeepHeaderWhenRefresh(true);
        //进入Activity就进行自动下拉刷新
        ptrFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrFrameLayout.autoRefresh();
            }
        }, 100);

        ptrFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            //在这里进行数据加载
            public void onRefreshBegin(PtrFrameLayout frame) {
                page = 1;
                loadList();
            }
        });
        ptrFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                page++;
                loadList();
            }
        });
    }

    private void loadList(){
        loadingDialog = new LoadingDialog(getContext());
        loadingDialog.setLoadingText("加载中...").show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = "";
                    if(type == null){
                        handler.sendMessage(handler.obtainMessage(2, null));
                    }else {
                        if (type.equals("plan")) {
                            url = "/getPlanSubmitList?projectid=" + projectId + "&page=" + String.valueOf(page) + "&limit=10";
                        } else if (type.equals("problem")) {
                            url = "/getQuestionSubmitList?projectid=" + projectId + "&page=" + String.valueOf(page) + "&limit=10";
                        }else{
                            url = "/getAllListByCreator?type="+type+"&page=" + String.valueOf(page) + "&limit=10";
                        }
                        String listStr = "";
                        if(!url.equals("")){
                            listStr = HttpUtil.get(url);
                        }else{
                            throw new Exception("list is null");
                        }
                        handler.sendMessage(handler.obtainMessage(1, listStr));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendMessage(handler.obtainMessage(2, null));
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String listStr = (String)msg.obj;
                    Gson gson=new Gson();
                    Map resultMap = gson.fromJson(listStr, Map.class);
                    if (resultMap != null && (boolean) resultMap.get("success")) {
                        List rows = (List) resultMap.get("rows");
                        int pages = Integer.parseInt((String)resultMap.get("pages"));

                        loadingDialog.close();
                        if(page==1) {
                            listData.clear();
                            listData.addAll(rows);

                            adapter.notifyDataSetChanged();
                            ptrFrameLayout.refreshComplete();

                            if(page < pages){
                                if (!ptrFrameLayout.isLoadMoreEnable()) {
                                    ptrFrameLayout.setLoadMoreEnable(true);
                                }
                            }
                        }else{
                            listData.addAll(rows);
                            adapter.notifyDataSetChanged();

                            ptrFrameLayout.loadMoreComplete(true);
                            if(page == pages){
                                if (ptrFrameLayout.isLoadMoreEnable()) {
                                    ptrFrameLayout.setLoadMoreEnable(false);
                                }
                            }
                        }
                    }else{
                        loadingDialog.close();
                        ptrFrameLayout.refreshComplete();
                        if (ptrFrameLayout.isLoadMoreEnable()) {
                            ptrFrameLayout.setLoadMoreEnable(false);
                        }
                    }
                    break;
                case 2:
                    loadingDialog.close();
                    ptrFrameLayout.refreshComplete();
                    if (ptrFrameLayout.isLoadMoreEnable()) {
                        ptrFrameLayout.setLoadMoreEnable(false);
                    }
                    break;
                case 3:
                    loadingDialog.close();
                    break;
            }
        }
    };

    public void LazyLoad(){
        //loadList();
    }

    Map clickedProblemMap = null;
    public void onItemClick(View view, int position) {
        clickedProblemMap = (Map) adapter.getItemAt(position);
        String type = (String)clickedProblemMap.get("type");
        if(type == null)type="";
        if(type.equals("0") || type.equals("1") || type.equals("2")){

            loadingDialog = new LoadingDialog(getContext());
            loadingDialog.setLoadingText("加载中...").show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Intent intent = new Intent(getActivity(), ProblemInfoActivity.class);
                        Bundle bundle=new Bundle();
                        String queid;
                        if(clickedProblemMap.containsKey("queid")){
                            queid = (String)clickedProblemMap.get("queid");
                        }else{
                            queid = (String)clickedProblemMap.get("id");
                        }
                        String listStr = HttpUtil.get("/getProblemInfoById?id="+queid);
                        Gson gson=new Gson();
                        Map resultMap = gson.fromJson(listStr, Map.class);
                        Iterator it = resultMap.entrySet().iterator();
                        while (it.hasNext()) {
                            Map.Entry entry = (Map.Entry) it.next();
                            Object key = entry.getKey();
                            Object value = entry.getValue();
                            if(value.getClass().getSimpleName().equals("String")) {
                                bundle.putString((String) key, (String) value);
                            }
                        }
                        handler.sendMessage(handler.obtainMessage(3, null));
                        intent.putExtras(bundle);
                        startActivityForResult(intent,0);
                    } catch (Exception e) {
                        handler.sendMessage(handler.obtainMessage(3, null));
                        e.printStackTrace();
                        Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_LONG).show();
                    }
                }
            }).start();

        }else if(type.equals("3")) {
            Intent intent = new Intent(getActivity(), ProjectActivity.class);
            Bundle bundle=new Bundle();
            bundle.putString("prjId",(String)clickedProblemMap.get("project"));
            bundle.putString("prjName",(String)clickedProblemMap.get("projectname"));
            bundle.putString("prjPercentdone",(String)clickedProblemMap.get("percentdone"));
            intent.putExtras(bundle);
            startActivityForResult(intent,0);
        }else if(type.equals("4")){
            Intent intent = new Intent(getActivity(), MessageContentActivity.class);
            Bundle bundle=new Bundle();
            bundle.putString("id",(String)clickedProblemMap.get("queid"));
            intent.putExtras(bundle);
            startActivityForResult(intent,0);
        }
    }
}
